Number of segments in a string¶
Time: O(N); Space: O(1); easy
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example 1:
Input: s = “Hello, my name is John”
Output: 5
Explanation:
There are five string “Hello”、“my”、“name”、“is”、“John”
[1]:
class Solution1(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
result = int(len(s) and s[-1] != ' ')
for i in range(1, len(s)):
if s[i] == ' ' and s[i-1] != ' ':
result += 1
return result
[2]:
sol = Solution1()
s = "Hello, my name is John"
assert sol.countSegments(s) == 5
[3]:
class Solution2(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
return len([i for i in s.strip().split(' ') if i])
[4]:
sol = Solution2()
s = "Hello, my name is John"
assert sol.countSegments(s) == 5